extends CharacterBody2D

@onready var enemyAni = $enemyAni

var dir =null
var speed =300 # 移动速度
var target = null # 目标
var hp = 10 #生命值

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	target = get_tree().get_first_node_in_group("player")
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if target:
		dir = (target.position - self.position).normalized()
		if dir.x < 0:
			enemyAni.flip_h = true
		else:
			enemyAni.flip_h = false
		velocity = dir * speed
		move_and_slide()
	pass

func enemy_hurt(hurt):
	self.hp -= hurt
	enemy_flash()

	if self.hp <= 0:
		enemy_dead()
		pass
	GameMain.animation_scene_obj.run_animation({
		"box":self,
		"ani_name":"enemies_hurt",
		"position":Vector2(1,1),
		"scale":Vector2(1,1)
	})
	pass
	
func enemy_dead():
	GameMain.animation_scene_obj.run_animation({
		"box":GameMain.duplicate_node,
		"ani_name":"enemies_dead",
		"position":self.global_position,
		"scale":Vector2(1,1)
	})
	
	GameMain.drop_item_scene_obj.gen_drop_item({
		"box":GameMain.duplicate_node,
		"ani_name":"glod",
		"position":self.global_position,
		"scale":Vector2(1,1)
	})
	self.queue_free()
	pass
	
func enemy_flash():
	$enemyAni.material.set_shader_parameter("flash_opacity",1)
	await get_tree().create_timer(0.1).timeout
	$enemyAni.material.set_shader_parameter("flash_opacity",0)
	pass
	
	
	
	
